<!-- 迷宫棋盘,这个组件只负责渲染棋盘，不负责游戏逻辑 -->
<template>
  <div class="maze-board" :style="gridStyle">
    <div 
      class="maze-cell" 
      v-for="(cell, index) in flatMaze" 
      :key="index"
      :class="getCellClass(cell)"
      :style="cellStyle"
    >
      <EffectItem  v-if="getEffectPosition(index)" />
    </div>
    
    <!-- 猫咪使用绝对定位，基于精确位置 -->
    <CatSprite 
      v-for="cat in cats" 
      :key="cat.id"
      :color="cat.color"
      :style="getCatStyle(cat)"
      class="cat-sprite"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import CatSprite from './CatSprite.vue';
import EffectItem from './EffectItem.vue';
// 引入props
const props = defineProps({
  maze: {
    type: Array,
    required: true,
    default: () => []
  },
  cellSize: {
    type: Number,
    default: 50
  },
  cats: {
    type: Array,
    required: true,
    default: () => []
  },
  effects: {
    type: Array,
    required: true,
    default: () => []
  }
})

// 计算网格样式
const gridStyle = computed(() => {
  if (!props.maze || props.maze.length === 0) {
    return {
      display: 'grid',
      gridTemplateColumns: 'repeat(1, 50px)',
      gridTemplateRows: 'repeat(1, 50px)',
      gap: '0px',
      width: 'fit-content',
      height: 'fit-content',
      border: '2px solid #333',
      position: 'relative' // 添加相对定位
    }
  }
  
  const cols = props.maze[0]?.length || 0
  return {
    display: 'grid',
    gridTemplateColumns: `repeat(${cols}, ${props.cellSize}px)`,
    gridTemplateRows: `repeat(${props.maze.length}, ${props.cellSize}px)`,
    gap: '0px', // 移除gap，使用边框来分隔
    width: 'fit-content',
    height: 'fit-content',
    border: '2px solid #333',
    position: 'relative' // 添加相对定位
  }
})

// 单元格样式
const cellStyle = computed(() => ({
  width: `${props.cellSize}px`,
  height: `${props.cellSize}px`,
  border: '1px solid #333',
  boxSizing: 'border-box'
}))

// 将二维数组扁平化为一维数组，便于Grid布局
const flatMaze = computed(() => {
  if (!props.maze || props.maze.length === 0) {
    return [0] // 返回一个默认格子
  }
  return props.maze.flat()
})

const getEffectPosition = (index) => {
  const effect = props.effects.find(effect => effect.position.row * props.maze[0].length + effect.position.col === index)
  return effect
}

// 获取猫咪的样式（使用精确位置）
const getCatStyle = (cat) => {
  const visualPos = {
    x: cat.exactPosition.x * 50 + (50-40)/2,
    y: cat.exactPosition.y * 50 + (50-40)/2
  }
  
  return {
    position: 'absolute',
    left: `${visualPos.x}px`,
    top: `${visualPos.y}px`,
    zIndex: 10
  }
}

// 根据单元格值返回对应的CSS类
const getCellClass = (cell) => {
  return {
    'bg-gray-800 border border-gray-600': cell === 1, // 墙壁样式
    'bg-white border border-gray-300 hover:bg-gray-100': cell === 0 // 路径样式
  }
}
</script>

<style scoped>
.maze-board {
  @apply mx-auto bg-gray-100;
}

.maze-cell {
  @apply flex items-center justify-center transition-all duration-200 ease-in-out cursor-pointer;
}

.cat-sprite {
  pointer-events: none; /* 防止猫咪阻挡点击事件 */
}
</style>